﻿using G19Glower.Shared;
using LedCSharp;
using System;

namespace G19Glower.App
{
    internal class GlowController : IGlowController, IDisposable
    {
        private System.Drawing.Color mLastColour;

        #region .ctor

        internal GlowController()
        {
            LogitechGSDK.LogiLedInit();
            LogitechGSDK.LogiLedSaveCurrentLighting();
        }

        #endregion

        #region IGlowController Members

        public void SetColor(byte r, byte g, byte b)
        {
            LogitechGSDK.LogiLedSetLighting(ToIntPercent(r), ToIntPercent(g), ToIntPercent(b));
            
            mLastColour = System.Drawing.Color.FromArgb(r, g, b);
        }

        public System.Drawing.Color GetColor()
        {
            return mLastColour;
        }

        private static int ToIntPercent(byte value)
        {
            if (value == 0)
            {
                return 0;
            }

            return 100 * value / 256;
        }

        #endregion

        #region IDisposable Support

        private bool mIsDisposed = false;

        protected virtual void Dispose(bool disposing)
        {
            if (mIsDisposed)
            {
                return;
            }

            mIsDisposed = true;

            LogitechGSDK.LogiLedRestoreLighting();
            LogitechGSDK.LogiLedShutdown();
        }

        ~GlowController()
        {
            // Do not change this code. Put cleanup code in Dispose(bool disposing) above.
            Dispose(false);
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        #endregion
    }
}